import React from 'react';
import './App.css';

const ws = new WebSocket('ws://localhost:8080/ws');

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      sendmsg: '',
      recvmsg: '',
    };
    this.onInputMsg = this.onInputMsg.bind(this);
    this.send = this.send.bind(this);
    this.createWebSocket();
  }

  onInputMsg(event) {
    this.setState({
      sendmsg: event.target.value,
    });
  }

  createWebSocket() {
    // const url = 'ws://localhost:8080/ws';
    // const ws = new WebSocket(url);

    ws.onopen = () => {
      console.log('web socket did connected');
      // setInterval(() => {
      //   console.log('loop printed as web socket connected.');
      // }, 1000);
    };

    ws.onmessage = (msg) => {
      const { data } = msg;
      this.setState({
        recvmsg: data,
      });
    };

    ws.onclose = (event) => {
      // TODO: handle close event
      console.log('socket closed connection: ', event);
    };

    ws.onerror = (error) => {
      // TODO: handle error event
      console.log('socket error: ', error);
    };
  }

  send() {
    const { sendmsg } = this.state;
    ws.send(sendmsg);
  }

  render() {
    const { sendmsg, recvmsg } = this.state;

    return (
      <div className="App">
        <div>
          <textarea value={sendmsg} onChange={this.onInputMsg} />
        </div>
        <button type="button" onClick={this.send}>
          发送消息
        </button>
        <div>
          <textarea value={recvmsg} />
        </div>
      </div>
    );
  }
}

export default App;
